package org.imlinker.status;

import java.util.ArrayList;

import javax.swing.ImageIcon;

import org.imlinker.core.Core;
import org.imlinker.gui.MainWindow;
import org.imlinker.gui.StatusDialog;
import org.imlinker.util.Images;

public class StatusManager extends Object {

	private MainWindow mainWindow;

	public StatusManager(final MainWindow window) {
		this.mainWindow = window;

		String iconDes = Core.getValue("status.icon");
		if (iconDes == null) {
			iconDes = "available";
		}
		statusIcon = Images.getIconByDes(iconDes);

		statuses = new ArrayList<String>();
		int size = Core.getElementSize("status.list");
		for (int i = 0; i < size; i++) {
			statuses.add(Core.getValue("status.list.element" + i));
		}
		if (size > 0) {
			status = statuses.get(0);
		}

		StatusPresence presence = new StatusPresence(statusIcon, status);
		window.setStatusByPresence(presence);
	}

	public void createStatusDialog() {
		new StatusDialog(null, this).setVisible(true);
	}

	public ImageIcon getIcon() {
		return statusIcon;
	}

	public String getStatus() {
		return status;
	}

	public ArrayList<String> getStatuses() {
		return statuses;
	}

	public void setStatus(final ImageIcon icon, final String paraStatus) {
		if (icon != null) {
			this.statusIcon = icon;

			String iconDes = icon.getDescription();
			Core.setValueAt("status.icon", iconDes);
		}

		if (paraStatus != null) {
			this.status = paraStatus;

			statuses.add(0, paraStatus);
			int size = statuses.size();
			for (int i = size - 1; i > 0; i--) {
				if (statuses.get(i).equals(paraStatus)) {
					statuses.remove(i);
				}
			}

			size = statuses.size();
			final int maxSize = 5;
			if (size > maxSize) {
				size = maxSize;
			}
			Core.deleteValue("status.list");
			for (int i = 0; i < size; i++) {
				Core.setValueAt("status.list.element" + i, statuses.get(i));
			}
		}

		Core.save();

		StatusPresence presence = new StatusPresence(this.statusIcon,
				this.status);
		mainWindow.setStatusByPresence(presence);
	}

	private ImageIcon statusIcon = Images.getAvailableIcon();

	private String status = "";

	private ArrayList<String> statuses;

}
